package com.chromatic.messages.controller;

import com.chromatic.messages.model.CompetitionsURL;
import com.chromatic.messages.repository.CompetitionsUrlRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/competitions_list")
public class CompetitionsUrlController {
    private final CompetitionsUrlRepository competitionsURLRepository;

    public CompetitionsUrlController(CompetitionsUrlRepository competitionsURLRepository) {
        this.competitionsURLRepository = competitionsURLRepository;
    }

@PostMapping("/save")
    public ResponseEntity<CompetitionsURL> saveCompetition(@RequestBody CompetitionsURL competition) throws JsonProcessingException {
        CompetitionsURL savedCompetition = competitionsURLRepository.save(competition);
        return ResponseEntity.ok(savedCompetition);
    }

    @GetMapping("/get/{id}")
    public ResponseEntity<CompetitionsURL> getCompetition(@PathVariable int id) {
        Optional<CompetitionsURL> competitionOptional = Optional.ofNullable(competitionsURLRepository.findById(id));
        if (competitionOptional.isPresent()) {
            CompetitionsURL competition = competitionOptional.get();
            return ResponseEntity.ok(competition);
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    @GetMapping("/getAll")
    public ResponseEntity<List<CompetitionsURL>> getAllCompetitions() {
        List<CompetitionsURL> competitions = competitionsURLRepository.findAll();
        if (!competitions.isEmpty()) {
            return ResponseEntity.ok(competitions);
        } else {
            return ResponseEntity.noContent().build();
        }
    }

    @GetMapping("/get-by-subject/{subject}")
    public List<CompetitionsURL> getCompetitionsBySubject(@PathVariable String subject) {
        return competitionsURLRepository.findBySubject(subject);
    }
}
